<template>
  <el-form :inline="true">
    <el-form-item label="一级分类">
      <el-select v-model="category1Id" placeholder="请选择" @change="changeCategory1Id" :disabled='isDisabled'>
        <el-option :label="c1.name" :value="c1.id" v-for="c1 in category1List" :key="c1.id"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="二级分类">
      <el-select v-model="category2Id" placeholder="请选择" @change="changeCategory2Id" :disabled='isDisabled'>
        <el-option :label="c2.name" :value="c2.id" v-for="c2 in category2List" :key="c2.id"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="三级分类">
      <el-select v-model="category3Id" placeholder="请选择" @change="changeCategory3Id" :disabled='isDisabled'>
        <el-option :label="c3.name" :value="c3.id" v-for="c3 in category3List" :key="c3.id"></el-option>
      </el-select>
    </el-form-item>
  </el-form>
</template>

<script>
  export default {
    name: 'CategoySelector',
    data() {
      return {
        category1Id: '', //一级分类id
        category2Id: '', //二级分类id
        category3Id: '', //三级分类id
        category1List: [], //一级分类数据
        category2List: [], //二级分类数据
        category3List: [], //三级分类数据
        isDisabled: false //设置三级导航是否可选
      }
    },
    created() {
      this.getCategory1List(); //在组件初始化时获取1级分类的信息
    },
    methods: {
      //获取一级分类信息
      async getCategory1List() {
        let result = await this.$API.category.getCategory1(); //调用接口
        if (result.code == 200) {
          this.category1List = result.data; //更新数据
        }
      },
      //改变一级分类时
      async changeCategory1Id(categoryId) {
        //置空二级,三级分类的id及数据
        this.category2Id = '';
        this.category3Id = ''
        this.category2List = [];
        this.category3List = [];
        //像父组件传递等级及id
        this.$emit('changeCategoryId', {
          level: 1,
          categoryId
        });
        let result = await this.$API.category.getCategory2(categoryId);
        if (result.code == 200) {
          this.category2List = result.data;
        }
      },
      //改变二级分类时
      async changeCategory2Id(categoryId) {
        this.category3Id = ''
        this.category3List = [];
        //像父组件传递等级及id
        this.$emit('changeCategoryId', {
          level: 2,
          categoryId
        });
        let result = await this.$API.category.getCategory3(categoryId);
        if (result.code == 200) {
          this.category3List = result.data;
        }
      },
      //改变三级分类时
      changeCategory3Id(categoryId) {
        //像父组件传递等级及id
        this.$emit('changeCategoryId', {
          level: 3,
          categoryId
        });
      }
    }
  }

</script>

<style>

</style>
